package com.auto.survey.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import androidx.customview.widget.ViewDragHelper

class SwipeLayout(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) {
    // 菜单状态
    private var isMenuOpen = false
    private var menuWidth = 0

    // 内容和菜单视图
    private lateinit var contentView: View
    private lateinit var menuView: View
    // 存储 dragHelper 引用的变量
    private lateinit var _dragHelper: ViewDragHelper
    // 初始化 dragHelper
    init {
        _dragHelper = ViewDragHelper.create(this, 1.0f, object : ViewDragHelper.Callback() {
            override fun tryCaptureView(child: View, pointerId: Int): Boolean {
                return child == contentView
            }

            override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int): Int {
                return Math.max(-menuWidth, Math.min(0, left))
            }

            override fun onViewPositionChanged(
                changedView: View,
                left: Int,
                top: Int,
                dx: Int,
                dy: Int
            ) {
                isMenuOpen = left <= -menuWidth / 2
                invalidate()
            }

            override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
                val targetX = if (contentView.left < -menuWidth / 2 || xvel < -500) {
                    -menuWidth
                } else {
                    0
                }

                // 使用存储的引用调用方法
                _dragHelper.settleCapturedViewAt(targetX, contentView.top)
                invalidate()
            }

            override fun getViewHorizontalDragRange(child: View): Int {
                return menuWidth
            }
        })
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        if (childCount != 2) {
            throw IllegalArgumentException("SwipeLayout must have exactly 2 children")
        }
        menuView = getChildAt(0)
        contentView = getChildAt(1)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        // 测量菜单视图（固定宽度）
        val menuWidthSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
        menuView.measure(menuWidthSpec, heightMeasureSpec)
        menuWidth = menuView.measuredWidth

        // 测量内容视图（占满剩余宽度）
        val contentWidthSpec = MeasureSpec.makeMeasureSpec(
            MeasureSpec.getSize(widthMeasureSpec),
            MeasureSpec.EXACTLY
        )
        contentView.measure(contentWidthSpec, heightMeasureSpec)

        // 设置自身尺寸
        setMeasuredDimension(
            MeasureSpec.getSize(widthMeasureSpec),
            contentView.measuredHeight
        )
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        // 布局菜单视图（右侧）
        menuView.layout(right - menuWidth, top, right, bottom)

        // 布局内容视图（初始位置）
        contentView.layout(left, top, right, bottom)
    }

    override fun computeScroll() {
        if (_dragHelper.continueSettling(true)) {
            invalidate()
        }
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        val action = ev.actionMasked

        // 如果菜单已打开，点击内容区域关闭菜单
        if (isMenuOpen && action == MotionEvent.ACTION_DOWN) {
            val x = ev.x
            val y = ev.y

            // 手动检查点击位置是否在 contentView 内
            if (x >= contentView.left && x <= contentView.right &&
                y >= contentView.top && y <= contentView.bottom) {
                closeMenu()
                return true
            }
        }

        return _dragHelper.shouldInterceptTouchEvent(ev)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        _dragHelper.processTouchEvent(event)
        return true
    }

    // 设置菜单宽度
    fun setMenuWidth(width: Int) {
        menuWidth = width
        requestLayout()
    }

    // 打开菜单
    fun openMenu() {
        isMenuOpen = true
        _dragHelper.smoothSlideViewTo(contentView, -menuWidth, 0)
        invalidate()
    }

    // 关闭菜单
    fun closeMenu() {
        isMenuOpen = false
        _dragHelper.smoothSlideViewTo(contentView, 0, 0)
        invalidate()
    }

    // 判断菜单是否打开
    fun isMenuOpen(): Boolean = isMenuOpen

    // 处理侧滑（由 ItemTouchHelper 调用）
    fun handleSwipe(dX: Float) {
        // 更新内容视图位置
        val newLeft = (contentView.left + dX).toInt()
        contentView.layout(
            Math.max(-menuWidth, Math.min(0, newLeft)),
            contentView.top,
            Math.max(-menuWidth, Math.min(0, newLeft)) + contentView.width,
            contentView.bottom
        )

        // 更新菜单状态
        isMenuOpen = contentView.left <= -menuWidth / 2
    }
}
